package jdklearning.concurrent.threadpool;


import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class ThreadPoolAndFuture {
	
	public static void main(String[] args) {
		ThreadPoolAndFuture t = new ThreadPoolAndFuture();
		t.pool1();
		t.pool2();
	}
	
	
	
	public void pool1(){
		try {
	    	ExecutorService executor = Executors.newFixedThreadPool(5);
		    Future<String> future = executor.submit(new Callable<String>() {
		        @Override
		        public String call() throws Exception {
		            System.out.println("call");
		            TimeUnit.SECONDS.sleep(3);
		            return "str";
		        }
		    });
			System.out.println(future.get());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void pool2(){
		ExecutorService threadPool = Executors.newCachedThreadPool();
        CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
        for(int i = 0; i < 5; i++) {
            final int taskID = i;
            cs.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                	TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(1, 5));
                    return taskID;
                }
            });
        }
        // 可能做一些事情
        for(int i = 0; i < 6; i++) {
            try {
//            	System.out.println(cs.take().isDone());
                System.out.println(cs.take().get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
		}
        
	}
}
